package com.flybutter.usagelab.ui.home

import com.google.android.material.tabs.TabLayout
import com.github.mikephil.charting.charts.BarChart
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.flybutter.usagelab.MainActivity
import com.flybutter.usagelab.databinding.FragmentHomeBinding
import com.flybutter.usagelab.utils.*
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.temporal.ChronoField
import kotlin.math.absoluteValue

private const val TODAY = 1
private const val YESTERDAY = 2
private const val WEEK = 3
private const val MONTH = 4

class HomeFragment : Fragment() {
    private var homeViewModel: HomeViewModel? = null
    private var binding: FragmentHomeBinding? = null
    private var rangeTab: TabLayout? = null
    private lateinit var usageList: RecyclerView
    private lateinit var onTabOnSelectedListener: TabLayout.OnTabSelectedListener

    @Volatile
    private lateinit var usageDataList: List<UsageStats>

    private var lastTabId: Int? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding!!.root
        rangeTab = binding!!.rangeTab
        usageList = binding!!.usageList
        usageList.layoutManager = LinearLayoutManager(this.requireActivity())
        initTab()
        loadUsageData(rangeTab!!.getTabAt(0)!!.id)
        (requireActivity() as MainActivity).run {
            addOnSearchListener { queryText ->
                if (!this@HomeFragment::usageDataList.isInitialized) {
                    return@addOnSearchListener
                }
                if (queryText.isBlank()) {
                    usageList.adapter = UsageListAdapter(
                        requireContext(),
                        usageList,
                        usageDataList
                    )
                }
                usageList.adapter = UsageListAdapter(requireContext(),
                    usageList,
                    usageDataList.filter { it.packageName.contains(queryText, true)}
                )
            }

            addDateSelectListener {
                renderData(it.first,it.second)
            }
        }
        return root
    }

    private fun initTab() {
        rangeTab!!.addTab(rangeTab!!.newTab().setId(TODAY).setText("今天"))
        rangeTab!!.addTab(rangeTab!!.newTab().setId(YESTERDAY).setText("昨天"))
        rangeTab!!.addTab(rangeTab!!.newTab().setId(WEEK).setText("本周"))
        rangeTab!!.addTab(rangeTab!!.newTab().setId(MONTH).setText("本月"))
        onTabOnSelectedListener = object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                if (tab.id == lastTabId)
                    return
                lastTabId = id
                loadUsageData(tab.id)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {}

            override fun onTabReselected(tab: TabLayout.Tab?) {}
        }
        rangeTab!!.addOnTabSelectedListener(onTabOnSelectedListener)
    }

    fun loadUsageData(type: Int) {
        var endTime = LocalDateTime.now()
        val startTime = when (type) {
            TODAY -> LocalDate.now().atStartOfDay()
            YESTERDAY -> {
                endTime = LocalDate.now().atStartOfDay()
                LocalDate.now().minusDays(1).atStartOfDay()
            }
            WEEK -> LocalDate.now().run {
                minusDays(dayOfWeek.value.toLong() - 1).atStartOfDay()
            }
            else -> LocalDate.now().run {
                minusDays(dayOfMonth.toLong() - 1).atStartOfDay()
            }
        }
        renderData(
            startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
            endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
        )
    }

    fun renderData(startTime: Long, endTime: Long) {
        Thread {
            val sm =
                requireActivity().getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
            usageDataList = sm.queryAndAggregateUsageStats(startTime, endTime)
                .values
                .sortedByDescending { it.totalTimeInForeground }
            requireActivity().runOnUiThread {
                usageList.adapter = UsageListAdapter(
                    this.requireContext(),
                    usageList,
                    usageDataList
                )
            }
        }.start()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
}